package com.wechat.ferry.utils;

import com.beust.jcommander.internal.Lists;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.GenericMultipleBarcodeReader;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class QRCodeParser {

    /**
     * 从图片中解析多个二维码
     */
    @SneakyThrows
    public static List<String> parseQRCodeFromImage(String imagePath) {
        File imageFile = new File(imagePath);
        try {
            // 读取图片
            BufferedImage image = ImageIO.read(new File(imagePath));

            // 创建 LuminanceSource 和 BinaryBitmap
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

            // 创建 MultiFormatReader 实例
            MultiFormatReader reader = new MultiFormatReader();

            // 设置解码提示（支持多种格式）
            Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);
            List<BarcodeFormat> formats = new ArrayList<>();
            formats.add(BarcodeFormat.QR_CODE);
            hints.put(DecodeHintType.POSSIBLE_FORMATS, formats);

            // 使用 GenericMultipleBarcodeReader 解析多个二维码
            GenericMultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
            Result[] results = multiReader.decodeMultiple(binaryBitmap, hints);

            // 提取二维码内容
            List<String> qrCodes = new ArrayList<>();
            for (Result result : results) {
                qrCodes.add(result.getText());
            }
            return qrCodes;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 6. 确保删除临时文件
            if (imageFile.exists()) {
                try {
                    boolean deleted = imageFile.delete();
                    if (!deleted) {
                        log.error("警告: 无法删除临时文件: " + imagePath);
                        // 可以添加重试逻辑或延迟删除
                        imageFile.deleteOnExit(); // 最后手段，在JVM退出时删除
                    }
                } catch (SecurityException e) {
                    log.error("安全异常，无法删除文件: " + e.getMessage());
                    imageFile.deleteOnExit();
                }
            }
        }
        return Lists.newArrayList();
    }
}